const mongoose = require('mongoose')
const utils = require('../common/utils')

// 创建数据表模型，该文件的名字，即games，就是数据表的名字
// 下面给 games 表声明的模型对象
let gameSchema = new mongoose.Schema({
  engName: String,
  chsName: String,
  developer: String,
  publisher: String,
  releaseDate: Date,
  playDate: Date,
  passDate: Date,
  platform: String,
  thumbnail: Array,
  picture: Array,
  remarks: String
})

//将对象模型注入到 mongoose中
// params1: 文档名称
// params2: 文档模型
var gameDb = mongoose.model('games', gameSchema)

async function modelSave(model) {
  if (model) {
    const gameModel = initModelInfo(model)
    var result = await gameModel.save()
    if (!result.errors) {
      return { success: true, message: '新增成功' }
    } else {
      return { success: false, message: '新增失败' }
    }
  } else {
    return { success: false, message: '缺少数据对象模型' }
  }
}

async function modelUpdate(model) {
  if (model) {
    const gameModel = initModelInfo(model)
    var result = await gameDb.findByIdAndUpdate(gameModel._id, gameModel)
    if (!result.errors) {
      return { success: true, message: '新增成功' }
    } else {
      return { success: false, message: '新增失败' }
    }
  } else {
    return { success: false, message: '缺少数据对象模型' }
  }
}

async function modelDelete(id) {
  if (id) {
    var count = await gameDb.findByIdAndDelete({ _id: id })
    return count
  } else {
    return { success: false, message: '缺少数据对象模型' }
  }
}

async function getExists(chsName) {
  if(chsName){
    var find = await gameDb.findOne({ chsName: chsName })
    return find
  } else {
    return { success: false, message: '缺少查询参数' }
  }
}

async function getCount() {
  var count = await gameDb.estimatedDocumentCount()
  return count
}

async function getList(pageNo, pageSize) {
  var list = await gameDb
    .find()
    .skip((parseInt(pageNo) - 1) * parseInt(pageSize))
    .limit(parseInt(pageSize))
  return list
}
// 初始化模型对象， 用于新增、修改操作
function initModelInfo(model) {
  const modelInfo = gameDb({
    _id: model._id,
    engName: model.engName,
    chsName: model.chsName,
    developer: model.developer,
    publisher: model.publisher,
    releaseDate: mode.releaseDate,
    playDate: model.publisher,
    passDate: model.passDate,
    platform: model.platform,
    thumbnail: model.thumbnail,
    picture: model.picture,
    remarks: model.remarks
  })
  return modelInfo
}

// 通过建 model 给 games 赋予增删改查等读写的功能
module.exports = {
  modelSave,
  modelUpdate,
  modelDelete,
  getExists,
  getCount,
  getList
}
